<?php
declare (strict_types=1);

namespace app\wxApi\controller;

use Ali\OSS\OSS;
use OSS\Http\RequestCore_Exception;
use think\facade\Cache;
use think\Exception;
use think\facade\Db;
use think\Request;
use think\Response;


class Files
{
    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request)
    {
        //
        try {
            $cache = Cache::get($request->post('token'));
            if (empty($cache)) {
                throw new Exception('登录失效', 3001);
            }
            $file = $request->file('file');
            $type = $request->post('type') ? $request->post('type') : 'images';
            if ($file) {
                // 获取文件名
                $fileName = $file->getOriginalName();
                // 上传文件到 OSS
                $oss = new OSS();
                $details = Db::name('examinee_baseinfo')->find($cache['id']);
                //判断是否存在照片如果存在则删除
                if (!empty($details['img'])) {
                    $result = $oss->deleteFile($details['img']);
                    if (!$result) {
                        throw new Exception('图片移除失败', 9002);
                    }
                }
                $result = $oss->uploadFile($fileName, $file->getRealPath(), 'examinee/avatar');

                if (isset($result['path']) && !empty($result['path'])) {
                    $img = str_replace('-internal','',$result['path']);
                    $update = Db::name('examinee_baseinfo')->where('id', '=', $cache['id'])->update(['img' =>$img]);
                    if (!$update) {
                        throw new Exception('保存照片失败', 9007);
                    }
                    // 更新缓存数据
                    $details['img'] = $img;
                    return success($details);
                }
            } else {
                throw new Exception('文件上传失败', 9005);
            }
        } catch (\Exception $e) {
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Response
     */
    public function delete($id, Request $request)
    {
        //
        return success([], 0, '文件删除成功');
        try {
            $oss = new OSS();
            if ($oss->deleteFile($request->get('filePath'))) {
                return success([], 0, '文件删除成功');
            } else {
                return error([], 9004, '文件删除失败');
            }
        } catch (\Exception $e) {
            return error([], 9005, $e->getMessage());
        }

    }

    /**
     * 上传视频
     * @param Request $request
     * @return Response
     */
    public function answer(Request $request)
    {
        try {
            $cache = Cache::get($request->post('token'));
            
            if (empty($cache)) {
                throw new Exception('登录失效', 3001);
            }
            $file = $request->file('file');
            if ($file) {
                 if($file->getSize()>500*1024*1024){
                    throw new Exception('视频大小超过了500M');
                }
                $condition = [
                    'examinee_id' => $cache['id'],
                    'active_id' => $request->post('active'),
                    'status' => 1
                ];
                $examineeDetails =  Db::name('examinee_baseinfo')->where(['id'=>$cache['id']])->find();
               
                
                $details = Db::name('answer')->where($condition)->find();
                
                $uploadPath = root_path() . 'public/uploads/video/'.$details['active_id'].'/';
                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0777, true);
                }
                
                $fileName=$file->getOriginalName();
                $ext = '.'.pathinfo($fileName, PATHINFO_EXTENSION);
                
                $saveName = $examineeDetails['name'].'_'.($details['type']==1?'朗诵':'主持').'_'.$details['level'].'级考试视频'.$ext;
                 
                // 把上传的视频按照指定格式移动到指定位置
                $info = $file->move($uploadPath, $saveName);
                //  移动成功后将数据保存到数据库
                $updateData = [
                    'id' => $details['id'],
                    'video_local_url' => 'uploads/video/'.$details['active_id'].'/'.$saveName,
                    'video_status' => 1,
                    'create_time' => time(),
                    'status' => 2
                ];
                $update = Db::name('answer')->update($updateData);
                if (!$update) {
                    throw new Exception('上传视频失败', 9007);
                }
                return success();
            } else {
                throw new Exception('视频上传失败', 9003);
            }
        } catch (\Exception $e) {
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }

    public function faceImg(Request $request)
    {
        //
        $cache = $request->cache;
        //  echo 1111;
        //     print_r($request->post());
        try {
            $cache = Cache::get($request->post('token'));
            if (empty($cache)) {
                throw new Exception('登录失效', 3001);
            }
           
            $file = $request->file('file');
            if ($file) {
                // 获取文件名
                $fileName = $file->getOriginalName();
                // 上传文件到 OSS
                $condition = [
                    'active_id' => $request->post('active'),
                    'examinee_id' => $cache['id']
                ];
                $examineeData = Db::name('answer')->where($condition)->find();
                if (empty($examineeData)) {
                    throw new Exception('非法操作', 9001);
                }
                $oss = new OSS();

                $result = $oss->uploadFile($fileName, $file->getRealPath(), 'examinee/face');

                if (isset($result['path']) && !empty($result['path'])) {
                    $updateData = [
                        'id' => $examineeData['id'],
                        'face_url' =>str_replace('-internal','',$result['path']),
                    ];
                    $update = Db::name('answer')->update($updateData);
                    if (!$update) {
                        throw new Exception('保存照片失败', 9007);
                    }
                    return success();
                }
            } else {
                throw new Exception('文件上传失败', 9005);
            }
        } catch (\Exception $e) {
            writeLogToDb('保存人脸失败', $cache['id'], 1, $e->getMessage());
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }
}
